// SlagCar/DailyCheckNewDetl/DailyCheckNewDetl.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //主表id
    entity: 'e_cheliangsanjian',
    //明细表id
    detailEntity: 'e_cheliangsanjianmingxi',
    //主表顶部字段配置
    mainFields:[
      {
        field_id: 'chepaihaoma;value',
        type: 'text',
        label: '车牌号码',
      },
      {
        field_id: 'jiashiyuan;value',
        type: 'text',
        label: '驾驶员',
      },
      {
        field_id: 'cheliangsanjianriqi',
        type: 'datetime',
        length: 'yyyy-MM-dd',
        label: '车辆三检日期',
      },
    ],
    //主表显示数据
    mainData:{},
    //主表提交数据
    mainIptData:{},
    //明细数据布局
    tableLayout: [
      /*{
        title: '出车前检车',
        dis: false,
        fields: [
          {
            field_id: 'chuchegonglishu',
            type: 'num',
            label: '出车公里数',
            precision: 2,
            tableType: 'main'
          },
          {
            field_id: 'chucheqiandianliang',
            type: 'num',
            label: '出车前电量',
            precision: 2,
            tableType: 'main'
          },

          {
            field_id: '1',
            type: 'splc',
            label: '人、车证照齐全',
            is_null: false,
            placeholder: '备注',
            tableType: 'detail'
          },
          {
            field_id: '2',
            type: 'splc',
            label: '润滑油量、电量足够',
            is_null: false,
            placeholder: '备注'
          },
          {
            field_id: '3',
            type: 'splc',
            label: '蓄电池正常',
            is_null: false,
            placeholder: '备注'
          },
        ]
      },
      {
        title: '行车途中检查',
        fields: [
          {
            field_id: '4',
            type: 'splc',
            label: '转向器、制动器工作正常',
            is_null: false,
            placeholder: '备注'
          },
          {
            field_id: '5',
            type: 'splc',
            label: '各种仪表工作正常',
            is_null: false,
            placeholder: '备注'
          },
          {
            field_id: '6',
            type: 'splc',
            label: 'GPS装置及智能盲区系统完好有效',
            is_null: false,
            placeholder: '备注'
          },
        ]
      },
      {
        title: '收车后检查',
        fields: [
          {
            field_id: '7',
            type: 'splc',
            label: '检查电量，有无漏水、漏油、漏电现象',
            is_null: false,
            placeholder: '备注'
          },
          {
            field_id: '8',
            type: 'splc',
            label: '检查清洁蓄电池',
            is_null: false,
            placeholder: '备注'
          },
          {
            field_id: '9',
            type: 'splc',
            label: '巡查车辆外部周围无异常',
            is_null: false,
            placeholder: '备注'
          },
        ]
      },*/
    ],
    //验证标识
    validFlag: false,
    //验证数据
    validObj:{},
    //临时表格数据
    formData: {},
    rowData:{},
    // 只读标识
    readonly: true,
    //编辑标识
    isEdit: false,

    //字段名称：根据不同检查步骤提交不同字段值
    formatFieldName: {
      '出车前检查': {
        checkResultName: 'chucheqianjianchajieguo',
        signName: 'chucheqianjianchayuanqianming',
        checkTimeName: 'chucheqianjianchashijian'
      },
      '行车途中检查': {
        checkResultName: 'xingchetuzhongjianchajieguo',
        signName: 'xingchetuzhongjianchayuanqianming',
        checkTimeName: 'xingchetuzhongjianchashijian'
      },
      '收车后检查': {
        checkResultName: 'shouchehoujianchajieguo',
        signName: 'shouchehoujianchayuanqianming',
        checkTimeName: 'shouchehoujianchashijian'
      },
    },

    //签名弹窗
    showSignature: false,
    watermark:[], //签名水印
  },


  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  // 验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },

  //字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val;

    //赋值
    this.setData({isEdit: true})
    this.setData({
      [`mainData.${id}`]: val
    });
    this.data.mainIptData[id] = val
    this.setData({isEdit: false})

    // this.data.formData[id] = val;

  },
  //备注 焦点离开输入框触发
  blurIpt(e){
    let {id} = e.currentTarget.dataset,
      {value} = e.detail;
    this.data.formData[`${id}_abstract`] = value;
  },
  //点解选择检查项目正常或异常
  bindSelect(e){
    let {id,val} = e.currentTarget.dataset;
    this.setData({
      [`formData.${id}`]: val
    });
  },
  //提交
  bindSubmit(){
    let {formData,rowData,tableLayout,entity,detailEntity,row_id,curType,pageTitle} = this.data;

    this.data.validObj = {}
    this.setData({
      validFlag: !this.data.validFlag,
    });
    let validObj = this.data.validObj;

    this.validForm(validObj).then(async valid => {
      if(valid) { // 表单验证通过
        console.log('表单验证通过', formData);

        let fmtData = this.formatSubmitData(formData);
        this.data.postMain = {...fmtData.main};
        this.data.postDetails = fmtData.details;

        //签名
        let watermark = [
          {
            content: '$time$',
            font: '18px sans-serif',
            position: {
              bottom: 8,
              left: 15
            }
          },
          {
            content: wx.getStorageSync('driver_car_name'),
            font: '16px sans-serif',
            position: {
              bottom: 30,
              left: 15
            }
          },
          {
            content: `检查结果：${fmtData.checkResult}`,
            font: '16px sans-serif',
            position: {
              bottom: 50,
              left: 15
            }
          },
          {
            content: curType,
            font: '16px sans-serif',
            position: {
              bottom: 70,
              left: 15
            }
          }
        ]
        this.setData({watermark})
        this.setData({showSignature:true})

      } else {  // 表单验证不通过
        console.log('表单验证不通过')
        wx.$toast('必填项不能为空！')
      }
    })
  },
  //提交接口
  submitData(){
    let {postMain,postDetails,curType,formatFieldName,detailEntity,entity} = this.data;
    wx.showLoading({mask: true});
    //获取当前时间
    let curTime = wx.$util.formatDate(new Date()),
      fieldName = formatFieldName[curType].checkTimeName;
    postMain[fieldName] = curTime;

    let postData = {
      "table": {
        "table_id": entity,
        "entitys":[{
          "entity": postMain,
          "details": [{
            "table_id": detailEntity,
            "entitys": postDetails
          }]
        }]
      }},
      url = `DynamicUpdate/dynamic_update_v3`;
    wx.$post(3,url,postData).then(async res =>{
      if (res.errcode != 0) return;
      let data = res.data.row[0],
        rid = data && data.entity[0];
      rid = rid && rid.row_id;
      // this.getRowData(rid);
      this.setData({readonly: true});
      if (curType === '收车后检查'){
        await this.checkFinished()
      }
      wx.$toast('提交成功',1000).then(() =>{
        wx.navigateBack({ delta:1 });
      });

    })
  },

  //作废
  bindCancel(e){
    let {type} = e.currentTarget.dataset,
      content = type === 'cancel' ? '确定作废当前检查？' : '确定作废当前检查并重新生成检查？'
    wx.showModal({
      title: '提示',
      content: content,
      success:(res)=>{
        if (res.confirm){
          wx.showLoading({mask: true})
          this.submitCancel().then(() =>{
            wx.$toast('作废成功',1000).then(() =>{
              //作废关闭页面
              if (type === 'cancel'){
                wx.navigateBack({ delta:1 });
              }
              //作废并新增
              if (type === 'cancelAdd'){
                this.prepare();
              }
            });
          })
        }
      }
    })
  },
  //提交作废接口
  submitCancel(){
    return new Promise(resolve => {
      let url = 'ZTAuth/CheLiangSanJian',data = {is_cancel: true};
      wx.$post(5,url,data).then(res =>{
        if (res.errcode != 0) return;
        resolve()
      })
    })
  },

  //确认签名
  onSign({detail}){
    this.setData({showSignature:  false});
    wx.showLoading({mask: true});
    wx.$uploadReq(detail).then(res =>{
      if (res.response.errcode != 0) {
        wx.$toast(res.errmsg);
        return
      }
      wx.hideLoading();
      let data = res.data.row[0];

      let {curType,formatFieldName} = this.data,
        fieldName = formatFieldName[curType].signName;
      fieldName && (this.data.postMain[fieldName] = data.filename);

      this.submitData();
    })
  },
  onSignCancel(){
    this.setData({showSignature:  false});
  },

  //车辆三检完成接口
  checkFinished(){
    return new Promise(resolve => {
      let {row_id} = this.data,
        url = `ZTAuth/CheLiangSanJian/${row_id}`;
      wx.$put(5,url).then(res =>{
        if (res.errcode != 0 )return;
        resolve();
      })
    })
  },


  /**
   * 1、获取车辆三检记录行号
   * 2、无返回行号（车检记录）时调用接口生成车检项目
   * 3、生成后获取行号后调用diy接口获取车检明细数据
   * 4、渲染车检项目
   */
  async prepare(row_id,check_type){
    let record,rid,items;
    if (!row_id){
      await this.getCheckRecord()
        .then(res =>{
          record = res;
        });
      if (!record){
        await this.buildCheckRecord(false).then(res => {
          record = res;
        });
      }

      rid = record?.row_id
      this.data.entity = record?.table_id;
    }else {
      rid = row_id;
    }
    this.data.row_id = rid;
    let checkTypeObj = {
      before: '出车前检查',
      going: '行车途中检查',
      after: '收车后检查',
      end: 'end'
    }

    await this.getCustomData().then(res =>{
      //主表数据
      let entity = res?.entity?.[0],

        arr = ['chucheqianjianchashijian','xingchetuzhongjianchashijian','shouchehoujianchashijian'],
        curType = check_type ? check_type
          : entity[arr[2]] ? 'end'
            : entity[arr[1]] ? 'after'
              : entity[arr[0]] ? 'going'
                : !entity[arr[0]] ? 'before'
                  : '';
      curType = checkTypeObj[curType]

      //页面传入检查类型时（管理端页面进入）、数据只读标识、当前操作员非该数据的司机时 -》 不可操作编辑数据，只读
      let readonly = check_type || entity?.is_readonly || (entity?.jiashiyuan != wx.getStorageSync('driver_row_id'));


      this.setData({mainData: entity,curType,readonly});
      //明细数据
      let details = res.detail1?.table_id === this.data.detailEntity ? res.detail1 : res.detail2;
      items = details.entity;
    })
    /*await this.getCheckItems(rid).then(res =>{
      items = res;
    })*/
    await this.initCheckItem(items)

    /*this.getCustomData().then(res =>{
      console.log(res);
    })*/
  },

  /**
   * 获取车辆三检记录行号
   * @param car {String} 车牌号码
   * @return {Promise<any>}
   */
  getCheckRecord(car){
    return new Promise(resolve => {
      let url = 'ZTAuth/CheLiangSanJian';
      wx.$get(5,url).then(res =>{
        if (res.errcode != 0 )return;
        let result = res.data.row?.[0];
        resolve(result)

      })
    })
  },

  /**
   * 生成车检记录
   * @return {Promise<any>}
   */
  buildCheckRecord(){
    return new Promise(resolve => {
      let url = 'ZTAuth/CheLiangSanJian',data = {is_generate: true,is_departed: true};
      wx.$post(5,url,data).then(res =>{
        if (res.errcode != 0) return;
        let result = res.data.row?.[0];
        resolve(result)
      })
    })
  },

  /**
   * 获取检查项目（通过主表行号查明细表数据）
   * @param rid 主表行id
   * @return {Promise<any>}
   */
  getCheckItems(rid){
    let {detailEntity} = this.data;
    return new Promise(resolve => {
      let url = 'DynamicQuery/query_dynamic_v3',
        data = {
          "table_id": detailEntity,
          "oby": `${detailEntity}.row_id desc`,
          "page":1,
          "limit":0,
          SearchWhere: {
            filters: [
              {
                CompareWith: `${detailEntity}.parent_row_id`,
                CompareValue: rid,
                Operator: '='
              }
            ],
            type: 'and'
          }
      };
      wx.$post(3,url,data).then(res =>{
        if (res.errcode != 0 )return;
        let result = res.data.row;
        resolve(result);
      })
    })
  },

  /**
   * 初始化车检项目
   * 1、获取车间明细表数据项目，并按前中后进行分类
   * 2、根据前中后检查类型，添加主表检查项目
   * 3、获取主表检查项目字段详细设置
   * @param items {Array} 项目集合
   */
  initCheckItem(items){
    let {curType} = this.data,
      obj = {},
      tableLayout = [],
      defData = {},
      curRowIds = [];
    items.forEach(item =>{
      let {row_id,jianchanarong,jianchajieguo,abstract} = item,
        type = item['xiangmumingchen;value'],
        index = 0;
      obj[type] = [...obj[type]||[],{
        field_id: `${row_id}`,
        type: 'splc',
        label: jianchanarong,
        is_null: false,
        placeholder: '备注',
        tableType: 'detail'
      }];
      jianchajieguo && (defData[row_id] = jianchajieguo)
      abstract && (defData[row_id + '_abstract'] = abstract)
      curType === type && curRowIds.push(row_id);
    });
    this.setData({curRowIds,formData: defData})
    // console.log(defData);
    // this.setData({formData: defData})

    /*let keys = Object.keys(obj);
    keys.forEach(item =>{
      tableLayout.push({
        title: item,
        fields: obj[item]
      })
    });
    this.setData({tableLayout})*/
    Promise.all([this.initBeforeItem(obj),this.initGoingItem(obj),this.initAfterItem(obj)]).then(res =>{
      this.setData({tableLayout: res});
      setTimeout(() =>{
        this.setData({curType});
      },100)
    })
  },

  /**
   * 初始化出车前检查项目
   * @param itemsObj {Object} 车检明细表中项目分类
   * @return {Promise<any>}
   */
  initBeforeItem(itemsObj){
    return new Promise(resolve => {
      let title = '出车前检查',
        {curType,readonly} = this.data,
        status = curType === title ? 1 : 2, //1 当前需要操作；2 该步骤已操作，显示数据；
        fieldsArr = ['chuchegonglishu','chucheqiandianliang'];
      status !== 1 && fieldsArr.unshift('chucheqianjianchashijian')
      if (status !== 1 || readonly) fieldsArr.push('chucheqianjianchayuanqianming')
      this.getFieldArr(fieldsArr).then(arr =>{

        let obj = {
          title,
          dis: status !== 1,
          fields: [...arr,...itemsObj[title]]
        };
        resolve(obj)
      })
    })
  },

  /**
   * 初始化行车途中检查项目
   * @param itemsObj {Object} 车检明细表中项目分类
   * @return {Promise<any>}
   */
  initGoingItem(itemsObj){
    return new Promise(resolve => {
      let title = '行车途中检查',
        {curType,readonly} = this.data,
        status = curType === title ? 1 : curType === '收车后检查' ? 2 : 3; //1 当前需要操作；2 该步骤已操作，显示数据；3 未到该步骤，不可操作
      if (status !== 1) {
        let fieldsArr = ['xingchetuzhongjianchashijian'];
        readonly && fieldsArr.push('xingchetuzhongjianchayuanqianming')
        this.getFieldArr(fieldsArr).then(arr =>{
          let obj = {
            title,
            dis: status !== 1,
            fields: [...arr,...itemsObj[title]]
          }
          resolve(obj)
        })
      }else {
        let obj = {
          title,
          dis: status !== 1,
          fields: itemsObj[title]
        }
        resolve(obj)
      }
    })
  },

  /**
   * 初始化收车后检查项目
   * @param itemsObj {Object} 车检明细表中项目分类
   * @return {Promise<any>}
   */
  initAfterItem(itemsObj){
    return new Promise(resolve => {
      let title = '收车后检查',
        {curType,readonly} = this.data,
        status = curType === title ? 1 : curType === 'end' ? 2 : 3, //1 当前需要操作；2 该步骤已操作，显示数据；3 未到该步骤，不可操作
        fieldsArr = ['shouchegonglishu','shouchehoudianliang','chongdianliang'];
      status !== 1 && fieldsArr.unshift('shouchehoujianchashijian')
      if (status !== 1 || readonly) fieldsArr.push('shouchehoujianchayuanqianming')
      this.getFieldArr(fieldsArr).then(arr =>{
        let obj = {
          title,
          dis: status !== 1,
          fields: [...arr,...itemsObj[title]]
        }
        resolve(obj)
      })
    })
  },

  /**
   * 格式化提交的数据
   * 1、循环对象，键为数字的是行号id，对应的值为检查结果；键为数字+ '_abstract'为该行的备注
   * 2、判断当前检查步骤总的检查结果，其中有一项异常，检查结果为异常，否则正常
   * 3、循环明细数组改为提交数据格式
   * @param data
   * @return {Object}
   */
  formatSubmitData(data){
    let {entity,detailEntity,row_id,curType,formatFieldName,curRowIds} = this.data,
      main = {row_id},
      checkResult = '正常',
      tempDetails = [];
    //1、循环对象，键为数字的是行号id，对应的值为检查结果；键为数字+ '_abstract'为该行的备注
    for (let key in data){
      let arr = key.match(/(\d*)_/),
        rid = arr ? arr[1] : key,
        name = arr ? 'abstract' : 'jianchajieguo';
      console.log(arr);
      if (curRowIds.indexOf(Number(rid)) === -1) continue;
      if (data[key]){
        let obj = tempDetails.find(item => item.row_id == rid)
        if (!obj)tempDetails.push({[name]: data[key],row_id: rid})
        else obj[name] = data[key];
      }
      //2、判断当前检查步骤总的检查结果，其中有一项异常，检查结果为异常，否则正常
      if (name === 'jianchajieguo' && data[key] !== '正常') checkResult = '异常'
    }

    let fieldName = formatFieldName[curType].checkResultName;
    fieldName && (main[fieldName] = checkResult);

    //循环明细数组改为提交数据格式
    let details = []
    tempDetails.forEach(item =>{
      details.push({
        "entity": item,
        "details":[]
      })
    })

    let postData = {
      "table": {
        "table_id": entity,
        "entitys":[{
          "entity": main,
          "details": [{
            "table_id": detailEntity,
            "entitys": details
          }]
        }]
      }}
    return {main,checkResult,details}
  },


  /**
   * 获取指定字段id的详细字段信息
   * @param fieldArr {Array} 字段id集合
   * @return {Promise<any>}
   */
  getFieldArr(fieldArr){
    return new Promise(resolve => {
      this.getCustomField().then(data =>{
        let arr = [];
        fieldArr.forEach(ite =>{
          let field = data.find(it => it.field_id === ite);
          if (field?.type === 'picture'){
            // field.is_take_a_photo = true;
            field.compress = true;
            field.watermark = () => this.getWatermark();
          }
          arr.push(field)
        });
        resolve(arr)
      })
    })
  },

  //获取模块字段
  getCustomField(){
    return new Promise(resolve => {
      let {entity,entityFields} = this.data,
        url = 'QX/PRO_select_field',
        post = {"table": entity,"fieldname":""};
      if (entityFields){
        resolve(entityFields);
        return
      }
      wx.showLoading({mask: true})
      wx.$post(4,url,post).then(res => {
        if (res.errcode != 0) return;
        wx.hideLoading();
        let data = res.data.row || [];
        this.data.entityFields = data;
        resolve(data)
      })
    })
  },

  //获取主明细表数据
  getCustomData(){
    return new Promise(resolve => {
      let {entity,row_id} = this.data,
        url = 'DynamicQuery/query_dynamic_v2',
        data = {table_id: entity , row_id};
      wx.$post(3,url,data).then(res =>{
        if (res.errcode != 0) return;
        let result = res.data.row?.[0];
        resolve(result)
      })
    })
  },

  getCustomMainData(){
    return new Promise(resolve => {
      let {entity,row_id} = this.data,
        url = 'DynamicQuery/query_dynamic_v3',
        data = {
          "table_id": entity,
          "oby": `${entity}.row_id desc`,
          "page":1,
          "limit":0,
          SearchWhere: {
            filters: [
              {
                CompareWith: `${entity}.row_id`,
                CompareValue: row_id,
                Operator: '='
              }
            ],
            type: 'and'
          }
        };
      wx.$post(3,url,data).then(res =>{
        if (res.errcode != 0) return;
        let result = res.data.row?.[0];
        resolve(result)
      })
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let {rid,check_type} = options;
    this.prepare(rid,check_type);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
